import React, { useMemo, useState } from "react";
import { Menu, Tooltip, Divider, Avatar, Popover, Button } from "antd";
import { useLocation, useNavigate } from "react-router-dom";
import { menuItems } from "../../config/menu";
import usePermission from "../../hooks/usePermission";
import "./style.less";
import Icon from "@/utils/icons";
import { LogoutOutlined, QuestionCircleOutlined } from "@ant-design/icons";

interface SideMenuProps {
  collapsed?: boolean;
}

const SideMenu: React.FC<SideMenuProps> = ({ collapsed }) => {
  const navigate = useNavigate();
  const location = useLocation();
  const permission = usePermission();
  // 模拟用户数据，实际项目中应该从用户状态中获取
  const user = {
    name: "张三",
    avatar: "https://api.dicebear.com/7.x/avataaars/svg?seed=user-1",
  };

  // 过滤菜单项，仅显示有权限的菜单
  const authorizedMenuItems = useMemo(() => {
    return menuItems.filter((item) => {
      // 跳过隐藏菜单
      if (item.hidden) {
        return false;
      }

      // 检查权限
      if (item.requireAuth && !permission.isAuthenticated()) {
        return false;
      }

      // 检查角色
      if (
        item.roles?.length &&
        !item.roles.some((role) => permission.hasRole(role))
      ) {
        return false;
      }

      return true;
    });
  }, [permission]);

  // 获取当前选中的菜单项
  const selectedKeys = useMemo(() => {
    const path = location.pathname;

    // 找到匹配的菜单项
    const matchedItem = authorizedMenuItems.find(
      (item) => path === item.path || path.startsWith(`${item.path}/`)
    );

    return matchedItem ? [matchedItem.key] : [];
  }, [location.pathname, authorizedMenuItems]);

  // 处理菜单点击
  const handleMenuClick = ({ key }: { key: string }) => {
    const item = authorizedMenuItems.find((item) => item.key === key);
    if (item) {
      navigate(item.path);
    }
  };

  // 创建菜单项，添加Tooltip
  const menuItemsWithTooltip = authorizedMenuItems.map((item) => ({
    key: item.key,
    icon: (
      <Tooltip
        title={item.title}
        placement="right"
        classNames={{ root: "menu-item-tooltip" }} // 替换弃用的 overlayClassName
      >
        <Icon name={item.icon} size={24} fill={item.color} />
      </Tooltip>
    ),
    label: item.title, // 即使不显示，也需要保留用于accessibility
    disabled: item.disabled,
  }));

  // 处理帮助中心点击
  const handleHelpClick = () => {
    navigate("/help");
  };

  // 处理退出登录
  const handleLogout = () => {
    // 这里应该调用登出API，清除token等
    localStorage.removeItem("auth_token");
    navigate("/login");
  };

  const userContent = (
    <div className="user-popover-content">
      <div className="user-info">
        <Avatar src={user.avatar} size="large" />
        <div className="user-name">{user.name}</div>
      </div>
      <Divider style={{ margin: "10px 0" }} />
      <Button
        type="text"
        icon={<LogoutOutlined />}
        onClick={handleLogout}
        block
      >
        退出登录
      </Button>
    </div>
  );

  return (
    <div className="side-menu-container">
      <div className="menu-brand">{/* 可以放置logo或者其他品牌元素 */}</div>

      {/* 主要菜单项 */}
      <Menu
        mode="inline"
        selectedKeys={selectedKeys}
        theme="light"
        inlineCollapsed={true}
        onClick={handleMenuClick}
        items={menuItemsWithTooltip.slice(0, 1)} // 只显示第一个菜单项
      />

      {/* 添加明确的分隔线 */}
      <Divider className="menu-divider" />

      {/* 其余菜单项 */}
      <Menu
        mode="inline"
        selectedKeys={selectedKeys}
        theme="light"
        inlineCollapsed={true}
        onClick={handleMenuClick}
        items={menuItemsWithTooltip.slice(1)} // 显示剩余菜单项
      />

      {/* 底部按钮区域 */}
      <div className="menu-bottom-actions">
        <Tooltip
          title="帮助中心"
          placement="right"
          classNames={{ root: "menu-item-tooltip" }}
        >
          <div className="bottom-action-item" onClick={handleHelpClick}>
            <Icon name="Help" size={24} fill="#121212" />
          </div>
        </Tooltip>

        <Popover
          content={userContent}
          trigger="click"
          placement="rightTop"
          overlayClassName="user-popover"
        >
          <div className="bottom-action-item">
            <Avatar src={user.avatar} size="small" />
          </div>
        </Popover>
      </div>
    </div>
  );
};

export default SideMenu;
